package com.rk.cust.application.service;

import com.rk.cust.infra.external.CustValidService;
import com.rk.cust.common.exception.CustException;
import com.rk.cust.common.exception.ErrorCode;
import com.rk.cust.domain.entity.Cust;
import com.rk.cust.domain.vo.CustStatus;
import com.rk.cust.infra.persistence.CustRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustAppService {

    @Autowired
    private CustRepository custRepository;

    @Autowired
    private CustValidService custValidService;

    private Cust getCust(Long id) {
        Cust cust = custRepository.queryCustById(id);
        if (null == cust.getId()) {
            throw new CustException(ErrorCode.CUST_NOT_EXISTS);
        }
        return cust;
    }

    public Cust queryCust(String id) {
        Cust cust = getCust(Long.valueOf(id));
        return cust;
    }

    public void addCust(Cust cust) {
        if (custValidService.valid(cust.getCertType().name(), cust.getCertNo())) {
            cust.setStatus(CustStatus.active);
        } else {
            cust.setStatus(CustStatus.unactivated);
        }
        custRepository.addCust(cust);
    }

    public void activeCust(String custId) {
        Cust cust = getCust(Long.valueOf(custId));
        cust.activate();
        custRepository.updateCust(cust);
    }

    public void update(Cust cust) {
        Cust last = getCust(cust.getId());
        last.setCorporation(cust.getCorporation());
        last.setCertType(cust.getCertType());
        last.setCertNo(cust.getCertNo());
        custRepository.updateCust(last);
    }
}
